package com.ono;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class Main {

	// http://api.ono3d.net/Token post 获取Token application/x-www-form-urlencoded
	// body:grant_type=password&username=zhangsikeke@126.com&password=zsk13992620405
	// 以下接口请求时Header添加 Authorization 值为Bearer+空格+token
	// get http://api.ono3d.net/explore/tags 获取所有tag
	// get http://api.ono3d.net/explore/tag/" + tag + "/?numPage=1&numPerPage=2000
	// 根据Tag标签获取模型列表
	// get http://api.ono3d.net/model/{idModel}/preview 下载zip包，html实现的stl预览
	// get http://api.ono3d.net/model/{idModel} 模型详情
	// 直接访问
	// https://web.ono3d.net/Home/ViewerModel/{idModel} 直接下载stl

//	  "animals",
//    "sculptures",
//    "decor",
//    "figurines",
//    "film",
//    "love"

	RequestHelper helper;
	final static String token = "Bearer g0PiXWnAJrn_fRc6l5azZLNE08P4VvLQZiqBiFJFhVlziL7wOIx6WYbtWj2_WXK2sVwzHHJHNCB4tU__Lv3WfMkBhJg-FqYJMldK3if8RZg2yThUXj8BD6NZMEKA5z53dXkW_vPzP5mnsOWUwbE-3Q-qk3rQuHUYTBdBEa3_Dh9xhLsgzaORMxS7p2lU878Iau_pjHXcqgOBn8ctvoLCVLJMqs-JUuvAe5fQVbaN3OAIHXd7OijxCr6Hwvd2_QY6tRZ8rsBhVyDW43LTRKB2sNo0eYHAKwpoKFeKxpiyKur_psfW9mu9_K_htUntKdT-ouhE6VNMQHNPREcXMyvZzvEN9dUPMDtCzYxXNX_MG8rf3rEoIbKEDC9c7jxQikQHJKvz1t8NCGI_EBk6asyMxiGjG3X_jT6EeBtaaaYkxOJ1OYcBKZ4l-A7v0tYq6gPNOzuk2fgw55qzv3lj1ryTPmIvyeNWPKbDsLbp4BpALbvEv9p0tFdZZdALaOx00SxfAtyGJE-N6qNWp_esw3-0fy2JTXnHML5rYhFaWkigDFo";

	// 总模型数
	private static int totalNum = 0;
	// 下载成功模型数
	private static int successNum = 0;
	// 下载失败模型数
	private static int failNum = 0;
	// 下载失败模型列表
	private static List<String> failNameAndIdList = new ArrayList<>();
	// 下载队列
	private static Queue<String[]> downloadQuene = new LinkedList<>();

	private static List<String> tags = new ArrayList<String>() {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		{
			add("animals");
			add("sculptures");
			add("decor");
			add("figurines");
			add("film");
			add("love");
		}
	};

	public static void main(String[] args) {

		Main m = new Main();
		m.helper = new RequestHelper();
		m.helper.setToken(token);
		// getModelList();
		m.getModelListExt();
		//System.out.println(m.getToken());
	}

	public void getModelList() {
		List<String[]> modelList = new ArrayList<>();
		int num = 0;
		for (String tag : tags) {
			String url = "http://api.ono3d.net/explore/tag/" + tag + "/?numPage=1&numPerPage=2000";
			String str = helper.get(helper.getAuthorizationRequest(url));
			JSONObject root = JSON.parseObject(str);
			JSONArray array = root.getJSONArray("response");
			System.out.println(tag + "共" + array.size() + "个");
			for (Object object : array) {
				JSONObject o = (JSONObject) object;
				String id = o.get("IdModel") + "";
				String name = o.get("Name") + "";
				modelList.add(new String[] { name, id, tag });
				System.out.println("id=" + id + ",name=" + name + ",tag=" + tag);
			}
			num += array.size();

		}
		totalNum = num;
		System.out.println("共" + num + "个模型");
		System.out.println("准备开始下载============>");
		for (String[] s : modelList) {
			boolean addSuccess = downloadQuene.offer(new String[] { s[0], s[1], s[2] });
			if (!addSuccess)
				System.err.println("添加" + s[0] + s[1] + s[2] + "失败");
		}
		downloadModel();
		System.out.println("<===========下载结束");
		System.out.println("下载成功" + successNum);
		System.out.println("下载失败" + failNum);
		System.out.println("下载失败列表");

	}

	public void downloadModel() {
		int index = 1;
		while (!downloadQuene.isEmpty()) {
			String[] s = downloadQuene.poll();
			String name = s[0];
			String id = s[1];
			String tag = s[2];
			System.out.println("开始下载" + index + "/" + totalNum);
			String url = "https://web.ono3d.net/Home/ViewerModel/" + id;
			String filePath = "/onoModel/" + tag + "/" + name + ".stl";
			boolean success = helper.download(helper.getRequest(url), filePath, name);
			if (success) {
				successNum++;
				index++;
			} else {
				failNum++;
				failNameAndIdList.add(name + "," + id + "," + tag);
				downloadQuene.offer(s);
			}
		}
	}

	public void getModelListExt() {
		StringBuilder sb = new StringBuilder();
		sb.append("<html>");
		sb.append("<head>");
		sb.append("<meta charset=\"UTF-8\"><title>ONO model list</title>"
				+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />"
				+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>");
		sb.append("</head>");
		sb.append("<body>");

		for (String tag : tags) {
			String url = "http://api.ono3d.net/explore/tag/" + tag + "/?numPage=1&numPerPage=2000";
			String str = helper.get(helper.getAuthorizationRequest(url));
			JSONObject root = JSON.parseObject(str);
			JSONArray array = root.getJSONArray("response");
			System.out.println(tag + ",共" + array.size() + "个");
			sb.append("<p>" + tag + ",共" + array.size() + "个</p>");
			for (Object object : array) {
				JSONObject o = (JSONObject) object;
				String id = o.get("IdModel") + "";
				String name = o.get("Name") + "";
				sb.append("<a href=\"https://web.ono3d.net/Home/ViewerModel/" + id + "\">" + name + "</a><br/>");
				System.out.println(id + "," + tag + "," + name);
			}
		}
		sb.append("</body>");
		sb.append("</html>");
		//writeFile("/index.html", sb.toString());
	}

	public void writeFile(String filePath, String content) {
		FileWriter writer = null;
		try {
			writer = new FileWriter(filePath);
			writer.write("");// 清空原文件内容
			writer.write(content);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public String getToken() {
		try {
			return OKHttpUtil.basePost("http://api.ono3d.net/Token", "grant_type=password&username=zhangsikeke@126.com&password=zsk13992620405").body().string();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
}
